{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9723b710",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time\n"
     ]
    }
   ],
   "source": [
    "def now():\n",
    "    print(\"time\")\n",
    "f = now\n",
    "f()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c089a55d",
   "metadata": {},
   "source": [
    "函数对象有一个__name__属性，可以拿到函数的名字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "93d325f2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'now'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "now.__name__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "671d6aff",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'now'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09409b47",
   "metadata": {},
   "source": [
    "如果我们希望增加now函数的功能，但不希望修改now的定义，这种在代码运行期间动态增加功能的方式，称之为“装饰器”（Decorator)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "787bca42",
   "metadata": {},
   "source": [
    "decorator就是一个返回函数的高阶函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c73a8697",
   "metadata": {},
   "source": [
    "我们借助python的@语法，把装饰器至于函数定义处："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "18a902e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def log(func):\n",
    "    def wrapper(*args, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        return func(*args, **kw)\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "bb3fa616",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call now():\n",
      "time\n"
     ]
    }
   ],
   "source": [
    "@log\n",
    "def now():\n",
    "    print('time')\n",
    "now()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b7b1e40",
   "metadata": {},
   "source": [
    "上面的log，因为它是一个装饰器，所以接收一个函数作为参数，并返回一个函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82f86e90",
   "metadata": {},
   "source": [
    "调用now函数不仅会运行now函数本身，还会再运行now函数前打印一行日志 "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8cf37f72",
   "metadata": {},
   "source": [
    "把@log放在now函数定义处，相当于执行了语句，now=log(now)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc9d3c9d",
   "metadata": {},
   "source": [
    "原来的now函数仍然存在，只是现在同名的now变量指向了新的函数，于是调用now将执行新函数，现在log函数中返回的wrapper函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb5e7022",
   "metadata": {},
   "source": [
    "如果装饰器本身需要传入参数，那就需要编写一个返回decorator的高阶函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e213d5f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def log(text):\n",
    "    def decorator(func):\n",
    "        def wrapper(*args, **kw):\n",
    "            print('%s %s():' % (text, func.__name__))\n",
    "            return func(*args, **kw)\n",
    "        return wrapper\n",
    "    return decorator\n",
    "@log('just test')\n",
    "def now():\n",
    "    print('test what?')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "629f3c19",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "just test now():\n",
      "test what?\n"
     ]
    }
   ],
   "source": [
    "now()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "867584a5",
   "metadata": {},
   "source": [
    "3层嵌套的效果，相当于now = log('execute')(now)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1ee30bc4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'wrapper'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "now.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b84b0121",
   "metadata": {},
   "source": [
    "函数也是对象，有__name__属性，经过装饰器之后的函数，名字已经从now变成了wrapper"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4043633a",
   "metadata": {},
   "source": [
    "因此需要把原始函数的__name__等属性赋值到wrapper()函数中，否则依赖函数签名的代码执行就会出错"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58f17c0e",
   "metadata": {},
   "source": [
    "一个完整的修饰器，写法如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "7df7222a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "def log(func):\n",
    "    @functools.wraps(func)\n",
    "    def wrapper(*args, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        return func(*args, **kw)\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "1de4bfc7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call kunzi():\n",
      "kunzikunzi\n"
     ]
    }
   ],
   "source": [
    "@log\n",
    "def kunzi():\n",
    "    print('kunzikunzi')\n",
    "kunzi()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e1d52159",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'kunzi'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "kunzi.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e289e494",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c4df1ca",
   "metadata": {},
   "source": [
    "Python的装饰器可以用函数实现，也可以用类实现。\n",
    "定义起来虽然复杂，但是使用起来非常灵活和方便"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a54c8ab9",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
